/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.giant.bean.transactions;

import com.giant.authentication.User;
import com.giant.entities.InOrder;
import com.giant.services.IServicioPersistenciaLocal;
import com.giant.services.ServicioPersistencia;
import com.giant.services.views.ServiceInventoryVLocal;
import com.giant.services.views.ServiceOrderVLocal;
import com.giant.views.InInventoryV;
import com.giant.views.InOrderV;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 *
 * @author Harold
 */
@ManagedBean
@SessionScoped
public class ReplicateOrderBean implements Serializable {

    /**
     * Relación con la interfaz que provee los servicios necesarios del vendedor
     */
    @EJB
    private ServiceInventoryVLocal serviceInventory;
    @EJB
    private ServiceOrderVLocal serviceOrder;
    @EJB
    private IServicioPersistenciaLocal persistence;
    @ManagedProperty(value = "#{detReplicateBean}")
    private DetReplicateBean detReplicateBean;
    private Date start;
    private Date finish;
    private String order;
    private boolean pay;
    private int ship = 0;
    private String param = "";
    private List<InInventoryV> allInventories;
    private int idOrder;
    private InOrderV orderById;
    private boolean isAdmin = false;
    //-----------------------------------------------------------
    // Atributos
    //-----------------------------------------------------------
    InOrder temp = new InOrder();
    /**
     * Representa un nuevo vendedor a ingresar
     */
    private InInventoryV inventory = new InInventoryV();
    private List<InInventoryV> tempDetailOrder;
    //listar ordenes
    private List<InOrderV> allOrders;
    private int id_user = 0;
    private List<User> dealers;

    //-----------------------------------------------------------
    // Getters y setters
    //-----------------------------------------------------------
    public ReplicateOrderBean() {
        persistence = new ServicioPersistencia();
        //Traer el usuario que esta registrado
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        Map<String, Object> sessionMap = externalContext.getSessionMap();
        User user = (User) sessionMap.get("user");
        id_user = user.getIdUser();
        isAdmin = (Boolean) sessionMap.get("isAdmin");
        dealers = (List<User>) sessionMap.get("dealers");
    }

    /**
     * Devuelve el objeto de vendedor actual
     *
     * @return vendedor Vendedor actual
     */
    public InInventoryV getInInventory() {
        return inventory;
    }

    /**
     * Modifica al vendedor actual
     *
     * @param vendedor Nuevo vendedor
     */
    public void setInventoryV(InInventoryV inventory) {
        this.inventory = inventory;
    }

    /**
     * Devuelve todos los vendedores del sistema
     *
     * @return vendedores Lista con todos los vendedores del sistema
     */
    public List<InInventoryV> getInventories() {
        if (allInventories == null) {
            allInventories = serviceInventory.getInventoryV();
        }
        return allInventories;
    }

    public void handleCityChange(String sql, String param) {
        System.out.println("entro");
        System.out.println(this.param);
        Map<String, String> map = new HashMap<String, String>();
        map.put(param, this.param);

        allInventories = this.serviceInventory.getInventoryVFilter(sql, map);

    }

    public void filterCriteria() {

        String sql = "SELECT i FROM InOrderV i where i.status=0";

        //add user filter depends on the profile   
        //admin all dealer's system
        if (!isAdmin) {
            if (!dealers.isEmpty()) {
                //seller all dealer's owns by the seller
                String deal="";
                for (int i = 0; i < dealers.size(); i++) {
                    deal+=dealers.get(i).getIdUser()+",";
                }
                deal=deal.substring(0, deal.length()-1);
                sql += " and i.idUser in(" + id_user+","+deal+")";
            } else {
                //dealer just dealer's orders 
                sql += " and i.idUser=" + id_user;
            }
        }

        if (order != null && !order.equals("")) {
            sql += " and i.idOrder=" + order;
        }
        if (pay == true) {
            sql += " and i.payment= 1";
        }
        if (ship != 0 && ship != -1) {
            sql += " and i.idShipment.idShipment= " + ship;
        }

        if (start != null && finish != null) {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateIni = format.format(start);
            String dateFin = format.format(finish);

            sql += " and i.dateOrder between {d '" + dateIni + "'} and {d '" + dateFin + "'}";

        }
        System.out.println(sql);
        allOrders = persistence.executeObjectSql(sql);
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public void addTempDetailOrder(InInventoryV inv) {
        if (tempDetailOrder == null) {
            tempDetailOrder = new ArrayList<InInventoryV>();
        }
        if (inv.getOrderQuantity() <= inv.getAvailableQuantity() && inv.getOrderQuantity() > 0) {
            tempDetailOrder.add(inv);
        } else {
            inv.setOrderQuantity(0);
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "The available quantity is invalid!"));
        }

        System.out.println("list size: " + tempDetailOrder.size());
    }

    public void testMethod(String test) {
        System.out.println("realizo test" + test);
    }

    public List<InOrderV> getOrders() {
        if (allOrders == null) {
            allOrders = serviceOrder.getOrderV();
        }
        return allOrders;
    }

    public List<InOrderV> getClosedOrders() {
        if (allOrders == null) {
            String query = "SELECT i FROM InOrderV i WHERE i.status =0";
            System.out.println(query);
            allOrders = persistence.executeObjectSql(query);
//            allDets=serviceDetOrder.getDetOrder();
        }

        return allOrders;
    }

    public Date getStart() {
        return start;
    }

    public void setStart(Date start) {
        this.start = start;
    }

    public Date getFinish() {
        return finish;
    }

    public void setFinish(Date finish) {
        this.finish = finish;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public boolean isPay() {
        return pay;
    }

    public void setPay(boolean pay) {
        this.pay = pay;
    }

    public int getShip() {
        return ship;
    }

    public void setShip(int ship) {
        this.ship = ship;
    }

    public int getIdOrder() {
        return idOrder;
    }

    public void setIdOrder(int idOrder) {
        this.idOrder = idOrder;
    }

    public String orderById() {
        System.out.println("entro orderById" + orderById.getIdOrder());

        detReplicateBean.setNoOrder(orderById.getIdOrder());
        detReplicateBean.setDateOrder(orderById.getDateOrder());
        detReplicateBean.setTotalOrder(orderById.getTotal());
        detReplicateBean.setSelectedOrderV(orderById);
//      orderById = serviceOrder.orderById(idOrder);

        return "orReplicateDet";
    }

    public InOrderV getOrderById() {
        return orderById;
    }

    public void setOrderById(InOrderV orderById) {
        this.orderById = orderById;
    }

    public DetReplicateBean getDetReplicateBean() {
        return detReplicateBean;
    }

    public void setDetReplicateBean(DetReplicateBean detReplicateBean) {
        this.detReplicateBean = detReplicateBean;
    }

    public boolean isIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(boolean isAdmin) {
        this.isAdmin = isAdmin;
    }
}
